package Controller

import (
	"github.com/gin-gonic/gin"
	"learningProject/vueGoProject/common"
	"learningProject/vueGoProject/model"
	"learningProject/vueGoProject/repository"
	"learningProject/vueGoProject/response"
	"strconv"
)

type IcategoryController interface {
	RestController
}

type CategoryController struct {
	Repository repository.CategoryRepository
}

func NewCategoryController() IcategoryController {
	repository := repository.NewCategoryRepository()
	common.DB.AutoMigrate(model.Category{}) // 自动迁移数据
	return CategoryController{Repository: repository}
}

func (cate CategoryController) Create(c *gin.Context) {
	var requestCategory model.Category
	if err := c.ShouldBind(&requestCategory); err != nil {
		response.Fail(c, nil, "数据验证错误，书籍分类名称为空！")
		return
	}

	category, err := cate.Repository.Create(requestCategory.Name)
	if err != nil {
		panic(err)
		//response.Fail(c,nil,"创建失败！")
		return
	}
	response.Success(c, gin.H{"category": *category}, "创建成功")
}

func (cate CategoryController) Update(c *gin.Context) {
	var requestCategory model.Category // 获取body中的参数
	if err := c.ShouldBind(&requestCategory); err != nil {
		response.Fail(c, nil, "数据验证错误，书籍分类名称为空！")
		return
	}

	// 获取path中的参数
	categoryId, _ := strconv.Atoi(c.Params.ByName("id"))
	updateCategory, err := cate.Repository.SelectById(categoryId)
	if err != nil { // 以categoryId为主键查询数据
		response.Fail(c, nil, "找不到id对应的数据")
		return
	}
	// 更新分类
	// 可以传 map,struct key:value
	category, err := cate.Repository.Update(*updateCategory, requestCategory.Name)
	if err != nil {
		response.Fail(c, nil, "更新失败")
		return
	}
	response.Success(c, gin.H{"category": *category}, "修改成功")
}

func (cate CategoryController) Show(c *gin.Context) {
	// 获取path中的参数
	categoryId, _ := strconv.Atoi(c.Params.ByName("id"))
	showCategory, err := cate.Repository.SelectById(categoryId)
	if err != nil { // 以categoryId为主键查询数据
		response.Fail(c, nil, "找不到id对应的数据")
		return
	}
	response.Success(c, gin.H{"category": showCategory}, "查询成功")
}

func (cate CategoryController) Delete(c *gin.Context) {
	// 获取path中的参数
	categoryId, _ := strconv.Atoi(c.Params.ByName("id"))
	if err := cate.Repository.DeleteById(categoryId); err != nil {
		response.Fail(c, nil, "删除失败")
		return
	}
	response.Success(c, nil, "删除成功")
}
